package gui.QualityControl;

import entities.ProductionOrder;
import gui.engraving.EngravingFrame;
import gui.engraving.EngravingPanel;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import net.miginfocom.swing.MigLayout;

import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 * GUI showing the list of orders that needs to be reported
 */
public class QCListOfOrders extends JPanel 
{
	private JTable table;
	private QCFrame myFrame;
	public DefaultTableModel model;
	private JButton createReport;
	public ArrayList<Object> listOfOrders;
	private JButton exitButton;
	private JButton button;

	public QCListOfOrders(QCFrame qualityControlFrame)
	{
		setBackground(new Color(173, 216, 230));
		this.myFrame = qualityControlFrame;
		setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("center:default:grow"),
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,}));
		
		JPanel panel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel.setBackground(new Color(173, 216, 230));
		panel.setBorder(new TitledBorder(null, "\u05E8\u05E9\u05D9\u05DE\u05EA \u05E4\u05E7''\u05E2\u05D5\u05EA \u05DC\u05D1\u05D3\u05D9\u05E7\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(panel, "6, 4, center, fill");
		panel.setLayout(new MigLayout("", "[][600px:n,grow,center][]", "[300px:n,grow][29px]"));
		
		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane, "cell 1 0,grow");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				if (arg0.getClickCount() == 2)
				{
					// Double click
					createReport(table.getSelectedRow());
				}
			}
		});
		table.setBorder(new TitledBorder(null, "", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05DB\u05DE\u05D5\u05EA", "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D9\u05D9\u05E6\u05D5\u05E8", "\u05D3\u05D9\u05D5\u05E4\u05D8\u05E8", "\u05E1\u05D5\u05D2", "\u05E4\u05E7''\u05E2"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(0).setPreferredWidth(50);
		table.getColumnModel().getColumn(0).setMinWidth(50);
		table.getColumnModel().getColumn(1).setResizable(false);
		table.getColumnModel().getColumn(1).setPreferredWidth(100);
		table.getColumnModel().getColumn(1).setMinWidth(100);
		table.getColumnModel().getColumn(2).setResizable(false);
		table.getColumnModel().getColumn(2).setPreferredWidth(50);
		table.getColumnModel().getColumn(2).setMinWidth(50);
		table.getColumnModel().getColumn(3).setResizable(false);
		table.getColumnModel().getColumn(3).setPreferredWidth(80);
		table.getColumnModel().getColumn(3).setMinWidth(80);
		table.getColumnModel().getColumn(4).setResizable(false);
		table.getColumnModel().getColumn(4).setPreferredWidth(110);
		table.getColumnModel().getColumn(4).setMinWidth(110);
		
		createReport = new JButton("יצירת דוח");
		createReport.setFont(new Font("Tahoma", Font.PLAIN, 13));
		createReport.setIcon(new ImageIcon(QCListOfOrders.class.getResource("/graphics/createReport.png")));
		createReport.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{

            		int rowNumber = table.getSelectedRow();
            		if (rowNumber==-1)
            		{
            			JOptionPane.showMessageDialog(myFrame,
            				    "יש לבחור ראשית פק''ע  מהרשימה.","שגיאה",JOptionPane.INFORMATION_MESSAGE);
            		}
            		else
            		{
	            		createReport.setEnabled(false);
	            		createReport(rowNumber);
	            		createReport.setEnabled(true);
            		}
        		
			
			}
		});
		
		button = new JButton("רענן");
		button.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{
				refreshList();
			}
		});
		button.setIcon(new ImageIcon(QCListOfOrders.class.getResource("/graphics/refreshOrders.png")));
		panel.add(button, "flowx,cell 1 1");
	
		
		panel.add(createReport, "cell 1 1,alignx center,aligny center");
	
		this.model = (DefaultTableModel) table.getModel(); 
		
		exitButton = new JButton("יציאה");
		exitButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		exitButton.setIcon(new ImageIcon(QCListOfOrders.class.getResource("/graphics/exit.png")));
		exitButton.addMouseListener(new MouseAdapter() 
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				Object[] options = {"כן","לא"};
        		int n = JOptionPane.showOptionDialog(myFrame, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
        		
        		if (n==0)
        		{
        			if (myFrame.qcClient != null)
                    {
                      try
                      {
                    	  myFrame.qcClient.close();
                      }
                      catch (Exception ignore)
                      {}
                     }
            		
            		System.exit(0);
        		}
			}
		});
		add(exitButton, "6, 6, center, center");
	}
/**
 * Initialize GUI data
 */
	public void setVariables(ArrayList<Object> response)
	{
		
		listOfOrders = (ArrayList<Object>) response;
    	    	 
        for (int i=1; i<=((int)listOfOrders.get(0));i++)
        {
        	ProductionOrder order = (ProductionOrder)listOfOrders.get(i);
            model.addRow(new Object[]{order.getQuantity(),order.getDateAsString(),order.getDiopter(),order.getType(),order.getOrderID()});
        }	
	}

	
	/**
	 * set GUI to report creation GUI
	 */
	private void createReport(int RowNumber)
	{
		myFrame.myNewReport.initializeByListOfOrdersTab((ProductionOrder)listOfOrders.get(RowNumber+1));
	}





/**
 * remove order from the table
 */

	public void removeFromTable(String orderID)
	{
		// get current number of orders in the table
		
		int ordersCounter = (int)(listOfOrders.get(0));
		
		
		// search the list for the orderID
		for ( int i=1; i<=ordersCounter ;i++ )
		{
			ProductionOrder temp = (ProductionOrder)listOfOrders.get(i);
		
			if (temp.getOrderID() == Integer.parseInt(orderID))
			{
				// remove order from the list
		
				listOfOrders.remove(i);
				// update the orders counter
				
				listOfOrders.set(0, ordersCounter-1);
				
				// clear the table
				for (int row=model.getRowCount()-1 ; row>=0;row--)
					model.removeRow(row);
				setVariables(listOfOrders);
				break;
			}
			
		}
		
	}
	
	
	/**
	 * Refresh list of orders to be reported
	 */
	protected void refreshList() 
	{
	
		
		// clear table
		// clear the table
		for (int row=model.getRowCount()-1 ; row>=0;row--)
			model.removeRow(row);
	
		// repopulate table
		
		 ArrayList<Object> message = new ArrayList<Object>();
	        message.add("initializeAllFieldsQualityControl");
	         
	        try 
	        {
	      //  	System.out.println("intialized for EngravingFrame");
	        	ArrayList<Object> response = myFrame.qcClient.call(message);
	        	setVariables(response);
 
	        } catch (Exception ex) {
	            Logger.getLogger(EngravingFrame.class.getName()).log(Level.SEVERE, null, ex);
	        }
	        
	
		
	
		
	}
	
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}
